<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 从路径总和II改到这里来的

        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(7)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(5)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g




        /* 
        1 时间O(n)
          空间O(n) n是栈递归的次数 不超过二叉树的节点
        2 思路
        */
        const pathSum = (root, targetNum) => {
            let ans = 0
            const cnt = new Map()
            cnt.set(0, 1)
            function dfs (node, s) {
                if (node === null) {
                    return
                }
                s += node.val
                ans += (cnt.get(s - targetNum) ?? 0)
                cnt.get(s, (cnt.get(s) ?? 0) + 1)
                dfs(node.left, s)
                dfs(node.right, s)
                cnt.set(s, cnt.get(s - targetNum) - 1)
            }
        }
        console.log(pathSum(a, 8));
    </script>
</body>

</html>